import turtle
import random

points = [[0,20], [0,0 ], [0, -20]]
index = 1
dis = 20


def gen_food():
    x = random.randint(-300, 300)
    y = random.randint(-300, 300)
    return [x, y]


def draw():
    global food
    turtle.clear()
    for point in points:
        turtle.up()
        turtle.goto(point)
        turtle.down()
        turtle.dot(20, 'red')
    turtle.up()
    turtle.goto(food)
    turtle.down()
    turtle.dot(20, 'cyan')
    new_point = points[0].copy()
    if abs(new_point[0]-food[0]) < 20 and \
            abs(new_point[1]-food[1]) < 20:
        food = gen_food()
    else:
        points.pop(-1)

    new_point[index] += dis
    points.insert(0, new_point)
    turtle.ontimer(draw, 500)


def func_up():
    global index, dis
    index =1
    dis = 20


def func_down():
    global index, dis
    index =1
    dis = -20


def func_left():
    global index, dis
    index = 0
    dis = -20


def func_right():
    global index, dis
    index = 0
    dis = 20


turtle.tracer(False)
food = gen_food()
draw()
turtle.onkeypress(func_up, 'Up')
turtle.onkeypress(func_down, 'Down')
turtle.onkeypress(func_left, 'Left')
turtle.onkeypress(func_right, 'Right')
turtle.listen()
turtle.done()

































